<template>
  <div>
    <div class="mt-4">
      <el-form inline>
        <el-row>
          <el-col :span="8">
            <el-form-item>
              <el-input
                  placeholder="请输入用户名"
                  v-model="searchKeyword"
                  clearable
                  @clear="getUserList"
              >
                <template #append>
                  <el-button :icon="Search" @click="getUserList" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div>
        <el-table
            :data="userList"
            border
            stripe
            @row-click="handleRowClick"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="nickname" label="姓名" />
          <el-table-column prop="username" label="账号" />
          <el-table-column prop="sex" label="性别" width="80">
            <template #default="scope">
              {{ scope.row.sex === 0 ? '女' : '男' }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="phoneNumber" label="电话" />
          <el-table-column prop="roleId" label="角色" width="80">
            <template #default="scope">
              {{ scope.row.roleId === 1 ? '管理员' : '健康管家' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog(scope.row.id)"
              >
                修改
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="removeOne(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
          v-model="editDialog"
          :title="dialogTitle"
          width="40%"
          class="custom-dialog"
      >
        <el-form
            :model="editUser"
            label-width="120px"
            class="custom-form"
            @submit.native.prevent
        >
          <el-form-item label="用户名">
            <el-input v-model="editUser.username" class="form-input" />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="editUser.nickname" class="form-input" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="editUser.sex" placeholder="请选择性别">
              <el-option label="女" value="0"></el-option>
              <el-option label="男" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="editUser.email" class="form-input" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="editUser.phoneNumber" class="form-input" />
          </el-form-item>

        </el-form>
        <template #footer>
          <el-button @click="editOne" type="primary">提交</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/axios/http';

const searchKeyword = ref('');
const userList = ref([]);
const editDialog = ref(false);
let dialogTitle = ref('');
const editUser = reactive({
  id: null,
  username: '',
  nickname: '',
  sex: null,
  email: '',
  phoneNumber: '',
  roleId: null
});

function getUserList() {
  try {
    const params = {
      keyword: searchKeyword.value || '%'
    };
    http.post('/lyy/get_user_list', params).then(
        (res) => {
          if (res.data.result === 'success') {
            userList.value = res.data.data.map(item => ({
              id: item.id,
              username: item.username,
              nickname: item.nickname,
              sex: item.sex,
              email: item.email,
              phoneNumber: item.phoneNumber,
              roleId: item.roleId
            }));
            if (userList.value.length === 0) {
              ElMessage.info('没有找到匹配的用户数据');
            }
          } else {
            ElMessage.error('获取用户数据失败：' + res.data.error);
          }
        }
    );
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
}

function showEditDialog(id) {
  const targetUser = userList.value.find(item => item.id === id);
  if (targetUser) {
    Object.assign(editUser, {
      id: targetUser.id,
      username: targetUser.username,
      nickname: targetUser.nickname,
      sex: targetUser.sex.toString(),
      email: targetUser.email,
      phoneNumber: targetUser.phoneNumber,
      roleId: targetUser.roleId.toString()
    });
    editDialog.value = true;
    dialogTitle.value = '修改用户信息';
  }
}

function editOne() {
  return new Promise((resolve, reject) => {
    const requestData = {
      id: editUser.id,
      username: editUser.username,
      nickname: editUser.nickname,
      sex: parseInt(editUser.sex),
      email: editUser.email,
      phoneNumber: editUser.phoneNumber,
      roleId: parseInt(editUser.roleId)
    };
    http.post('/lyy/edit_user', requestData)
        .then(res => {
          if (res.data.result === 'success') {
            ElMessage.success('修改成功');
            editDialog.value = false;
            getUserList();
            resolve();
          } else {
            ElMessage.error('修改失败: ' + res.data.error);
            reject();
          }
        })
        .catch(error => {
          console.error('修改失败:', error);
          ElMessage.error('修改失败，请稍后重试');
          reject();
        });
  });
}

const removeOne = (userId) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        try {
          const res = await http.post('/lyy/delete_user', { id: userId });
          if (res.data.result === 'success') {
            ElMessage.success('删除成功');
            await getUserList();
          } else {
            ElMessage.error('删除失败: ' + res.data.error);
          }
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败，请稍后重试');
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}

.custom-dialog {
  padding: 20px;
  box-sizing: border-box;
}

.custom-form {
  width: 100%;
}

.form-input {
  width: 100%;
}
</style>